$(function(){
  creatStar("#star",50);
 

  localStorage.setItem("disportCor", 0);
  localStorage.setItem("disportErr", 0);
  getList();

  var time = 60;

  $("#count-down").text(time);
  var count =  setInterval(function(){
    var lastTime = parseInt($("#count-down").text());
    if(lastTime === 0){
      $('body').append('<div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 4;"></div>');
      var cNum = parseInt(localStorage.getItem("disportCor"));
      var eNum = parseInt(localStorage.getItem("disportErr"));
      var cNum2 = parseInt(localStorage.getItem("disportCor")) + parseInt(localStorage.getItem("disportErr"));
      var tolNum = parseFloat(cNum/cNum2 + cNum).toFixed(2);
      var correctRate = parseInt(cNum/cNum2*10000);
      correctRate = correctRate/100;



      disportQustion.pop();//注意移除答题的最后一道题，没有结果
      //数组转字符串,判断题默认点击正确为0，点击错误为1，跳过为-1；
      var disportQustionLast = disportQustion.join(";");
      var disportAnswerLast = disportAnswer.join(";");

      if(cNum < 6){//过关题目数量
        window.Interface.challengeResults({
          results:"fail",
          starType:"fun", //游戏game,理财finance,生活life，健康healthy，育儿child,娱乐fun
          score:tolNum,//总分
          question:disportQustionLast,//问题
          answer:disportAnswerLast,//答案
          rightCnt:cNum,//正确答题数
          errorCnt:eNum//错误答题数
        },function(res){
          showResults("disport","fail",0,0,0,0,false);
        });
      }else{
        window.Interface.challengeResults({
          results:"success",
          starType:"fun", //游戏game,理财finance,生活life，健康healthy，育儿child,娱乐fun
          score:tolNum,//总分
          question:disportQustionLast,//问题
          answer:disportAnswerLast,//答案
          rightCnt:cNum,//正确答题数
          errorCnt:eNum//错误答题数
        },function(res){
          showResults("disport",res.type,cNum,correctRate+"%",tolNum,res.ranking,res.isSend);
        });
      }


      //正确答题，正确率，总分
      //disportResults.postResults(cNum,CorrectRate+"%",tolNum);
      //板块，结果（擂主challenger，过关success,失败fail）,正确答题，正确率，总分,排名
      //showResults(disportResults.start,disportResults.type,cNum,CorrectRate+"%",tolNum,disportResults.rank);


      clearInterval(count);
    }else{
      $("#count-down").text(lastTime-1);
    }

  },1000);


});

//定义全局变量，问题和答案
var disportQustion =[];
var disportAnswer =[];


//板块，结果（擂主challenger，过关success,失败fail）,正确答题，正确率，总分,排名
function showResults(start,type,cNum,rate,tolNum,rank,isSend){
  $.ajax({
    type: "GET",
    url: "pages/pop-"+type+".html",
    success: function(data){

      $("body").append(data);
      $(".pop-box").addClass("pop-"+start);
      $("#pop-cor").text(cNum);
      $("#pop-rate").text(rate);
      $("#pop-tol").text(tolNum);
      $("#pop-rank").text(rank);
      if(isSend){
        $(".pop-box .text").show();
      }else{
        $(".pop-box .text").hide();
      }


      $(".pop-box .close").on("click",function(){
        window.location.href='index.html';
      });

      $(".pop-box .btn-blue").on("click",function(){
        window.Interface.challengeNum({},function(res){
          if(res.fun<3){
            if(type==="fail"){
              window.location.href= start+'.html';//返回挑战页
              window.Interface.tracking('娱乐星球', '挑战结果页','不服再战');
            }else{
              window.location.href='index.html';//返回首页
              window.Interface.tracking('娱乐星球', '挑战结果页','挑战新高');
            }
          }else{
            showPop("每天最多挑战3次哟，去试试其他项目吧！","确定","index.html");
          }
            // $("#challenge-parenting").text(res.child);
            // $("#challenge-disport").text(res.fun);
            // $("#challenge-game").text(res.game);
            // $("#challenge-money").text(res.finance);
            // $("#challenge-life").text(res.life);
            // $("#challenge-health").text(res.healthy);
        });
      });
      $(".pop-box .btn-green").on("click",function(){
        if(type==="fail"){
          window.location.href='index.html';//返回首页
        }else{
          window.Interface.shareUrl({
            starType:start
          },function(res){
            //window.location.href = res.url;
          });
          if(type==="success"){
            window.Interface.tracking('娱乐星球', '挑战结果页','分享战绩');
          }else{
            window.Interface.tracking('娱乐星球', '挑战结果页','分享擂主');
          }
        }
      });
      $(".pop-box a").on("click",function(){
        var rel = $(this).attr("rel");
        if(rel === "lottery.html"){
          window.Interface.tracking('娱乐星球', '挑战结果页','幸运抽奖');
        }
      });

    }
  });
}




function getList(){

  var arr = [];
  var $jsonData;

  $.ajax({
    type: "GET",
    url: "data/disport.json",
    success: function(data){
      $jsonData = $(data.qustion);


      var leg = $(data.qustion).length;
      for(var i = 1; i<=leg; i++){
        arr.push(i);
      };
      var nid = parseInt(randomInteger(1,leg));
      arr.remove(nid);
      getQustion(nid);
    }
  });






//获取问题
function getQustion(nid){
  $jsonData.each(function(n,v){
    if(v.id === nid){
      creatAnswer(v);
      return false;
    }
  })
}

//生成问题
function creatAnswer(data){
disportQustion.push(data.id);
  $("#option-list").empty();
  $("#answer-tit").text(data.tit);

  var cStr = data.answerCorrent;
  var eStr = data.answerSupplement;
  var cArr = [];
  cArr = cStr.split("");

  var cArrN = [];
  $(cArr).each(function(n,v){
    cArrN[n] = {},
    cArrN[n].t = "t"+n;
    cArrN[n].v = v;
  });

  var eArr = [];
  eArr = eStr.split("");
  var eArrN = [];
  var cleg = cArrN.length;
  $(eArr).each(function(n,v){
    eArrN[n] = {},
    eArrN[n].t = "t"+(cleg + n);
    eArrN[n].v = v;
  });


  var lastArr = cArrN.concat(eArrN);
  lastArr = shuffle(lastArr);
  function shuffle(arr){
    var i,j,temp;
    for(i = arr.length-1;i>0;i--){
      j = Math.floor(Math.random() * (i + 1));
      temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
    return arr;
  }

  $(lastArr).each(function(n,v){
    var span = $('<span>'+v.v+'</span>').data("t",v.t);
    $("#option-list").append(span)
  });


  judgeAnswer(cArrN)//传递正确答案数组

}
//答题
function judgeAnswer(data){
  var anArr = [];
  var anLeg = $(data).length;
  var corArrT = [];
  $(data).each(function(n,v){
    corArrT[n] = v.t;
  });


  var st,appendQustion = true;
  var aArrText = [];
  $("#option-list span").off("click.answer").on("click.answer",function(){

    if($(this).hasClass("cur")){
      $(this).removeClass("cur");
      aArrText.pop();
    }else{
      $(this).addClass("cur");
      var asLeg =  $("#option-list span.cur").length;
      anArr[(asLeg-1)] = $(this).data("t");
      aArrText.push($(this).text());
    }

    if($("#option-list span.cur").length === anLeg){
      

      if(judge(anArr,data)){
        showTips("correct", "回答正确");
        var cNum = parseInt(localStorage.getItem("disportCor"))+1;
        localStorage.setItem("disportCor", cNum);
        $("#result-correct span").text(cNum);
        
      }else{
        $("#option-list").addClass("error");
        $("#option-list span").each(function(n,v){
          if($.inArray($(this).data("t"),corArrT) >=0 ){
            $(this).addClass("cor");
          }
        })
         showTips("error","回答错误");
          var cNum = parseInt(localStorage.getItem("disportErr"))+1;
          localStorage.setItem("disportErr", cNum);
          $("#result-error span").text(cNum);
      }
      var aArrTextLast = aArrText.join("");
      disportAnswer.push(aArrTextLast);
      appendQustion = false;
      st = setTimeout(function(){
        hideTips();
        var nid = getID();
        arr.remove(nid);
        getQustion(nid);
        $("#option-list").removeClass("error");
        clearTimeout(st);
      },1000);

    }
  });

  $(".btn-box .btn-next").off("click.nx").on("click.nx",function(){
    clearTimeout(st);
    if(appendQustion){
      disportAnswer.push("-1");
    }
    hideTips();
    $("#option-list").removeClass("error");
    var nid = getID();
    arr.remove(nid);
    getQustion(nid);

  });


function judge(anArr,data){
  var ns = true;
  $(anArr).each(function(n,v){
    if(v !== data[n].t){
      ns = false;
    }
  })
  return ns;
}





}

//随机ID
function getID(){
    var len = arr.length;
    if(len<=10){
      getList();
      //console.log("tikucuowu")
    }else{
      var i = Math.ceil(Math.random() * (len ))%len;
      return arr[i];
    }
}

//显示隐藏提示
function showTips(cn,text){
  $("#answer-tips").addClass(cn).fadeIn().find("span").text(text);
}
function hideTips(){
  $("#answer-tips").removeClass("correct error").hide();
  $("#option-list .col").removeClass("correct error")
}

}

